﻿using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Web;
using System.Web.Http;
using System.Net.Http.Headers;
using OfficeOpenXml;
using System.Text;

public class FileListController : ApiController
{
    private const string TemplatePath = @"C:\template";

    [System.Web.Http.HttpGet]
    [Route("api/files")]
    public IHttpActionResult GetAllFiles()
    {
        try
        {
            // 验证目录是否存在
            if (!Directory.Exists(TemplatePath))
            {
                return Json(new
                {
                    code = 200,
                    msg = "Directory not found",
                    data = (object)null
                });
            }

            //// 获取所有文件名
            //var files = Directory.EnumerateFiles(TemplatePath)
            //                   .Select(Path.GetFileName) // 仅获取文件名
            //                   .ToList();
            // 获取所有文件名并去掉扩展名
            var files = Directory.EnumerateFiles(TemplatePath)
                               .Select(file => Path.GetFileNameWithoutExtension(file)) // 获取文件名并去掉扩展名
                               .ToList();
            return Json(new
            {
                code = 200,
                msg = "OK",
                data = files
            });
        }
        catch (UnauthorizedAccessException ex)
        {
            return Json(new
            {
                code = 403,
                msg = $"Access denied: {ex.Message}",
                data = (object)null
            });
        }
        catch (IOException ex)
        {
            return Json(new
            {
                code = 500,
                msg = $"IO Error: {ex.Message}",
                data = (object)null
            });
        }
        catch (Exception ex)
        {
            return Json(new
            {
                code = 500,
                msg = $"Server Error: {ex.Message}",
                data = (object)null
            });
        }
    }
    //-----------------------------
    private const string TemplatePathm = @"C:\templatem";

    [System.Web.Http.HttpGet]
    [Route("api/filesm")]
    public IHttpActionResult GetAllFilesm()
    {
        try
        {
            // 验证目录是否存在
            if (!Directory.Exists(TemplatePathm))
            {
                return Json(new
                {
                    code = 404,
                    msg = "Directory not found",
                    data = (object)null
                });
            }

            // 获取所有文件名
            var files = Directory.EnumerateFiles(TemplatePathm)
                               .Select(Path.GetFileName) // 仅获取文件名
                               .ToList();

            return Json(new
            {
                code = 200,
                msg = "OK",
                data = files
            });
        }
        catch (UnauthorizedAccessException ex)
        {
            return Json(new
            {
                code = 403,
                msg = $"Access denied: {ex.Message}",
                data = (object)null
            });
        }
        catch (IOException ex)
        {
            return Json(new
            {
                code = 500,
                msg = $"IO Error: {ex.Message}",
                data = (object)null
            });
        }
        catch (Exception ex)
        {
            return Json(new
            {
                code = 500,
                msg = $"Server Error: {ex.Message}",
                data = (object)null
            });
        }
    }



    //-----------------------------
    private const string TemplatePaths = @"C:\模拟工艺单_锻造";

    // 将IsExcelFile方法移到类级别
    private static bool IsExcelFile(string filePath)
    {
        var ext = Path.GetExtension(filePath)?.ToLower();
        return ext == ".xls" || ext == ".xlsx";
    }

    [System.Web.Http.HttpGet]
    [Route("api/filess")]
    public IHttpActionResult GetAllFiless()
    {
        try
        {
            if (!Directory.Exists(TemplatePaths))
            {
                return Json(new
                {
                    code = 404,
                    msg = "Directory not found",
                    data = (object)null
                });
            }

            var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);

            // 合并查询，避免重复枚举文件
            var files = Directory.EnumerateFiles(TemplatePaths)
                .Select(f => new
                {
                    name = Path.GetFileName(f),
                    url = $"{baseUrl}/api/filess/download/{Uri.EscapeDataString(Path.GetFileName(f))}",
                    previewUrl = IsExcelFile(f) ? $"{baseUrl}/api/filess/preview/{Uri.EscapeDataString(Path.GetFileName(f))}" : null
                })
                .ToList();

            return Json(new
            {
                code = 200,
                msg = "OK",
                data = files
            });
        }
        catch (UnauthorizedAccessException ex)
        {
            return Json(new
            {
                code = 403,
                msg = $"Access denied: {ex.Message}",
                data = (object)null
            });
        }
        catch (IOException ex)
        {
            return Json(new
            {
                code = 500,
                msg = $"IO Error: {ex.Message}",
                data = (object)null
            });
        }
        catch (Exception ex)
        {
            return Json(new
            {
                code = 500,
                msg = $"Server Error: {ex.Message}",
                data = (object)null
            });
        }
    }

    [System.Web.Http.HttpGet]
    [Route("api/filess/download/{filename}")]
    public HttpResponseMessage DownloadFile(string filename)
    {
        try
        {
            // 增强安全验证
            if (string.IsNullOrWhiteSpace(filename) ||
               filename.Contains("..") ||
               filename.Contains("/") ||
               filename.Contains("\\"))
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid file name");
            }

            // 硬编码路径测试（调试后还原）
            var trueTemplatePath = @"C:\模拟工艺单_锻造";
            var filePath = Path.Combine(trueTemplatePath, filename);

            // 确保路径仍在模板目录内（防御性编程）
            if (!filePath.StartsWith(trueTemplatePath))
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Path traversal attempt");
            }

            if (!File.Exists(filePath))
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "File not found");
            }

            var fileBytes = System.IO.File.ReadAllBytes(filePath);
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(fileBytes)
            };

            result.Content.Headers.ContentDisposition =
                new ContentDispositionHeaderValue("attachment")
                {
                    FileName = filename
                };

            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(filename));

            return result;
        }
        catch (UnauthorizedAccessException)
        {
            return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Access denied");
        }
        catch (IOException ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, $"IO Error: {ex.Message}");
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, $"Server Error: {ex.Message}");
        }
    }
    // 新增预览接口
    [System.Web.Http.HttpGet]
    [Route("api/filess/preview/{filename}")]
    public HttpResponseMessage PreviewFile(string filename)
    {
        try
        {
            // 1. 解码文件名并验证路径
            var decodedFilename = Uri.UnescapeDataString(filename);
            var filePath = Path.Combine(TemplatePaths, decodedFilename);

            // 强制规范化路径（处理可能的 ../ 问题）
            filePath = Path.GetFullPath(filePath);

            // 2. 严格路径安全检查（确保路径在模板目录内）
            if (!filePath.StartsWith(TemplatePaths, StringComparison.OrdinalIgnoreCase))
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "非法路径访问");
            }

            // 3. 验证文件存在性
            if (!File.Exists(filePath))
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "文件不存在");
            }

            // 4. 转换为 HTML 并返回
            var htmlContent = ConvertExcelToHtml(filePath);

            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StringContent(htmlContent, Encoding.UTF8, "text/html"); // 关键：指定 MIME 类型
            return response;
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, $"预览生成失败: {ex.Message}");
        }
    }

    private string ConvertExcelToHtml(string filePath)
    {
        using (var package = new ExcelPackage(new FileInfo(filePath)))
        {
            var sb = new StringBuilder();
            sb.Append("<html><head><style>");
            sb.Append("table { border-collapse: collapse; width: 100%; }");
            sb.Append("td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; }");
            sb.Append("tr:nth-child(even) { background-color: #f2f2f2; }");
            sb.Append("</style></head><body>");

            foreach (var worksheet in package.Workbook.Worksheets)
            {
                sb.Append($"<h2>{worksheet.Name}</h2>");
                sb.Append("<table>");

                // 添加表头
                sb.Append("<tr>");
                for (int col = 1; col <= worksheet.Dimension.End.Column; col++)
                {
                    sb.Append($"<th>{GetCellValue(worksheet.Cells[1, col])}</th>");
                }
                sb.Append("</tr>");

                // 添加数据行
                for (int row = 2; row <= worksheet.Dimension.End.Row; row++)
                {
                    sb.Append("<tr>");
                    for (int col = 1; col <= worksheet.Dimension.End.Column; col++)
                    {
                        sb.Append($"<td>{GetCellValue(worksheet.Cells[row, col])}</td>");
                    }
                    sb.Append("</tr>");
                }

                sb.Append("</table>");
            }

            sb.Append("</body></html>");
            return sb.ToString();
        }
    }



    [HttpGet]
    [Route("api/debug/checkfile")]
    public IHttpActionResult CheckFile(string filename)
    {
        var decodedFilename = Uri.UnescapeDataString(filename);
        var filePath = Path.Combine(TemplatePaths, decodedFilename);
        bool exists = File.Exists(filePath);
        return Ok(new { exists, filePath });
    }

    private string GetCellValue(ExcelRange cell)
    {
        if (cell.Value == null) return "";

        // 处理特殊格式
        if (cell.Style.Numberformat.Format.StartsWith("yyyy") && cell.Value is double)
        {
            return DateTime.FromOADate((double)cell.Value).ToString("yyyy-MM-dd");
        }

        return cell.Text.Trim().Replace("\n", "<br/>"); // 保留换行符
    }





}